<?php

include_once ('Logging.php');

# 群脉
class MaiscrmClass
{

    const API_URL = 'https://business-api.maiscrm.com';
    const API_URL_TEST = 'https://staging-business-api.maiscrm.com';


    const ACCESSTOKEN_TEST = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE2MDYxODEzOTYsImV4cCI6NDc1OTc4MTM5NiwiaXNzIjoicG9ydGFsIiwiYXVkIjoib3BlbkFQSSIsImFpZCI6IjVlNzg3MmE3NzNlZTEyMDBmYjFiZWMzMiIsInN1YiI6ImFwcDo1ZmJjNjIxNGFhMDEwNTA2MDYyNDI4ZjMiLCJ1bmlxIjoiMTU1NjMxNzI0ODVmYmM2MjE0ZjBhYjc1LjE2ODU5MjUwIn0.1uUWBzZLBA4pRb9t_a_8TLig96uxydgRCGfOKT3xXcM';
    const ACCESSTOKEN = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE2MDg1MTczMDMsImV4cCI6NDc2MjExNzMwMywiaXNzIjoicG9ydGFsIiwiYXVkIjoib3BlbkFQSSIsImFpZCI6IjVmOTZhMTE0NzlmNzU2NWUyMzBmYmU1OCIsInN1YiI6ImFwcDo1ZmUwMDZiN2Q5NTRlYzM5N2UzN2RkMjgiLCJ1bmlxIjoiNTI3NDYwMzQwNWZlMDA2Yjc3N2Y3NjEuMjQyODg4NTkifQ.-DltYPrzsKsnLNAQS4XOEbsFcVUAVnfcrFnCOSqKRY8';
    private $isDebug = false;

    public function __construct($flag = true)
    {
        $this->isDebug = $flag;
    }

    # 1. 抓取前一分钟状态为（paid 待接单，unassigned 待分配，accepted 待提货/待发货），配送方式为（express 邮寄）的订单资料
    public function Test($paid = 'paid', $unassigned = 'unassigned', $accepted = 'accepted', $express = 'express')
    {
        $token = '?access_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE2MDYxODEzOTYsImV4cCI6NDc1OTc4MTM5NiwiaXNzIjoicG9ydGFsIiwiYXVkIjoib3BlbkFQSSIsImFpZCI6IjVlNzg3MmE3NzNlZTEyMDBmYjFiZWMzMiIsInN1YiI6ImFwcDo1ZmJjNjIxNGFhMDEwNTA2MDYyNDI4ZjMiLCJ1bmlxIjoiMTU1NjMxNzI0ODVmYmM2MjE0ZjBhYjc1LjE2ODU5MjUwIn0.1uUWBzZLBA4pRb9t_a_8TLig96uxydgRCGfOKT3xXcM';
        $url = (($this->isDebug) ? self::API_URL_TEST : self::API_URL).'/v2/ec/searchOrders'.$token;
        $data = [];
        $data['status'] = [$paid,$unassigned,$accepted];
//        $data['updatedAt']['start'] = time();
        $data['updatedAt']['start'] = 1606807514;
//        $data['updatedAt']['end'] = time()+60;
        $data['updatedAt']['end'] = 1607325936;
        $data['updatedAt']['type'] = 'CLOSE_OPEN';
        $data['deliveryMethod'] = $express;
        $data = json_encode($data);
        $result = $this->http_post($url, $data,false,'json');
        $result = json_decode($result, true);

        return array("result" => $result, "data" => json_encode($result));
    }

   public function GetOrders(array $paramete)
    {
        $token = '?access_token='.(($this->isDebug) ? self::ACCESSTOKEN_TEST : self::ACCESSTOKEN);
        $url = (($this->isDebug) ? self::API_URL_TEST : self::API_URL).'/v2/ec/searchOrders'.$token;
        $data['status'] = [$paramete['paid'],$paramete['unassigned'],$paramete['accepted']];
        $data['listCondition'] = ['page'=>$paramete['page'],'perPage'=>$paramete['pageSize']];
        $data['updatedAt']['start'] = $paramete['start'];
        $data['updatedAt']['end'] = $paramete['end'];
        $data['updatedAt']['type'] = $paramete['type'];
        $data['deliveryMethods'] = [$paramete['express'],$paramete['express2']];
        $data = json_encode($data);
        $result = $this->http_post($url, $data,false,'json');
        $result = json_decode($result, true);
        return $result;
    }

    public function GetMemberInfo($mid)
    {
//        $mid = '5fc5d58b67d6436eeb183dac';
        $token = '?access_token='.(($this->isDebug) ? self::ACCESSTOKEN_TEST : self::ACCESSTOKEN);
        $url = (($this->isDebug) ? self::API_URL_TEST : self::API_URL).'/v2/members/'.$mid.$token;
        $result = $this->http_get($url);
        $result = json_decode($result, true);
        return $result;
    }


    /**
     * GET 请求
     * @param string $url
     */
    private function http_get($url)
    {
        $url = urldecode($url);
        $oCurl = curl_init();
        if (stripos($url, "https://") !== FALSE) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
            curl_setopt($oCurl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
        }



        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
         curl_setopt($oCurl, CURLOPT_HTTPHEADER, array('Content-Type: application/json;charset=utf-8'));

        $log = new Logging();
        $log->lfile('Maiscrm_http_get');
        $log->lwrite(($url));

        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        $log->lwrite(($sContent));
        curl_close($oCurl);
        if (intval($aStatus["http_code"]) == 200) {
            return $sContent;
        } else {
            return false;
        }
    }

    /**
     * POST 请求
     * @param string $url
     * @param array $param
     * @param boolean $post_file 是否文件上传
     * @return string content
     */
    private function http_post($url, $param, $post_file = false, $contenttype = '')
    {
        $timeout = 8;
        $oCurl = curl_init();
        if (stripos($url, "https://") !== FALSE) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        if (empty($contenttype)) {
            curl_setopt($oCurl, CURLOPT_HTTPHEADER, array('application/x-www-form-urlencoded'));
        } else if ($contenttype == "json") {
            curl_setopt($oCurl, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8'));

        }

        if (is_string($param) || $post_file) {
            $strPOST = $param;
        } else {
            $aPOST = array();
            foreach ($param as $key => $val) {
                $aPOST[] = $key . "=" . urlencode($val);
            }
            $strPOST = join("&", $aPOST);
        }

        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($oCurl, CURLOPT_POST, true);
        curl_setopt($oCurl, CURLOPT_POSTFIELDS, $strPOST);
        curl_setopt($oCurl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($oCurl, CURLOPT_CONNECTTIMEOUT, $timeout);
        curl_setopt($oCurl, CURLOPT_TIMEOUT, $timeout);

        $log = new Logging();
        $log->lfile('Maiscrm_http_post');
        $log->lwrite(($url));
        $log->lwrite((json_encode($param)));
        $log->lwrite(($strPOST));
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        $log->lwrite(($sContent));
        return $sContent;
    }
}
//$a = new MaiscrmClass();
//$b = $a->GetMemberInfo();
//var_dump($b);